<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form ref="loginU" @submit="login">
      <van-field
        name="mobileU"
        placeholder="请输入手机号"
        v-model="user.mobile"
        :rules="formRules.mobile"
      >
        <i slot="left-icon" class="toutiao toutiao-shouji"></i>
      </van-field>
      <van-field
        placeholder="请输入验证码"
        v-model="user.code"
        :rules="formRules.code"
      >
        <i slot="left-icon" class="toutiao toutiao-yanzhengma"></i>
        <template #button>
          <van-count-down
            :time="time"
            format="重新获取验证码ss 秒"
            v-if="sending"
            @finish="sending = false"
          />
          <van-button
            size="small"
            round
            native-type="button"
            @click="sendCode"
            v-else
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="loading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Sendmss, UserLogin } from "@/api/user";
export default {
  data() {
    return {
      user: {
        mobile: "",
        code: "",
      },
      formRules: {
        mobile: [
          { required: true, message: "请填写手机号" },
          { pattern: /^1[3|4|5|7|8][0-9]\d{4,8}$/, message: "手机号格式错误" },
        ],
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{4,6}$/, message: "验证码格式错误" },
        ],
      },
      time: 5000,
      sending: false,
      loading: false,
    };
  },
  methods: {
    async sendCode() {
      this.$refs.loginU.validate("mobileU");
      try {
        await Sendmss(this.user.mobile);
        this.$toast.success("验证码发送成功");
        this.sending = true;
      } catch (error) {
        if (error.response) {
          this.$toast.fail(error.response.data.message);
        } else {
          this.$toast.fail("网络错误");
        }
      }
    },
    async login() {
      try {
        this.loading = true;
        const res = await UserLogin(this.user);
        // console.log(res);
        localStorage.setItem("token", res.data.data.token);
        this.$toast.success("登录成功");
      } catch (error) {
        if (error.response) {
          this.$toast.fail(error.response.data.message);
        } else {
          this.$toast.fail("网络错误");
        }
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style>
</style>